package com.hxz.graduationdesign.util;

import com.hxz.graduationdesign.pojo.entity.User;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static com.hxz.graduationdesign.util.FormattingTool.parseNumber;

public class BilibiliUserCrawler {


    public static Map<String, String> getUserInfoByUid(String uid) {
        // 使用 WebDriverManager 自动下载并配置 ChromeDriver
        WebDriverManager.chromedriver().setup();

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.addArguments("--disable-blink-features=AutomationControlled");
        options.addArguments("--disable-gpu");
        options.addArguments("--no-sandbox");
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--disable-web-security");
        options.addArguments("--ignore-certificate-errors");
        options.setExperimentalOption("useAutomationExtension", false);
        options.addArguments("--headless");

        WebDriver driver = new ChromeDriver(options);
        WebDriverWait wait = new WebDriverWait(driver, 20);
        Map<String, String> userInfo = new HashMap<>();

        try {
            driver.get("https://www.bilibili.com");

            driver.get("https://www.bilibili.com");
            driver.manage().addCookie(new Cookie("SESSDATA", "3533ab04%2C1760165697%2Cd9572%2A41CjC4GyVWoP3QwcZYai9Eugq66IIiZUVavXZQ-J3E_aWRmFatBkChePndsVKAhGWXvvcSVkJfTWRrOU44X0d0N3B0RC0zaGQ2YzI0eDBCQnJhN2Flem9ieVRnVUZ4SGZQR251MTh2d3NOdUd2dHFVZE84MVNBZXhvbDJOZVdINzJ4VTNzUURhdm1nIIEC",
                    ".bilibili.com", "/", null));
            driver.manage().addCookie(new Cookie("bili_jct", "cc7c196ff8fcd88bc68b76949ad4ec39",
                    ".bilibili.com", "/", null));
            driver.manage().addCookie(new Cookie("sid", "7sdhrhoc",
                    ".bilibili.com", "/", null));
            driver.navigate().refresh();

            String url = "https://space.bilibili.com/" + uid;
            driver.get(url);

            wait.until(ExpectedConditions.presenceOfElementLocated(
                    By.cssSelector("div.upinfo-detail")
            ));

            ((JavascriptExecutor) driver).executeScript("window.scrollBy(0, 300)");
            Thread.sleep(1000);

            try {
                WebElement usernameElement = wait.until(ExpectedConditions.visibilityOfElementLocated(
                        By.cssSelector("div.upinfo-detail__top div.nickname")
                ));
                userInfo.put("username", usernameElement.getText());
            } catch (Exception e) {
                System.err.println("获取用户名失败: " + e.getMessage());
                userInfo.put("username", "未知");
            }

            try {
                WebElement levelElement = wait.until(ExpectedConditions.presenceOfElementLocated(
                        By.cssSelector("a.level i.level-icon")
                ));
                String levelClass = levelElement.getAttribute("class");
                String level = levelClass.replaceAll(".*?_level_(\\d+).*", "$1");
                userInfo.put("level", level.isEmpty() ? "0" : level);
            } catch (Exception e) {
                System.err.println("获取等级失败: " + e.getMessage());
                userInfo.put("level", "0");
            }

            try {
                WebElement genderElement = driver.findElement(By.cssSelector("div.gender i"));
                String genderIconClass = genderElement.getAttribute("class");
                if (genderIconClass.contains("male")) {
                    userInfo.put("gender", "男");
                } else if (genderIconClass.contains("female")) {
                    userInfo.put("gender", "女");
                } else {
                    userInfo.put("gender", "未知");
                }
            } catch (Exception e) {
                System.err.println("获取性别失败: " + e.getMessage());
                userInfo.put("gender", "未知");
            }

            try {
                WebElement medalElement = driver.findElement(By.cssSelector("div.fans-medal div.medal"));
                String medalName = medalElement.findElement(By.cssSelector("div.medal-name")).getText();
                String medalLevel = medalElement.findElement(By.cssSelector("div.medal-level")).getText();
                userInfo.put("medal", medalName + " Lv." + medalLevel);
            } catch (Exception e) {
                userInfo.put("medal", "无粉丝勋章");
            }

            try {
                WebElement followElement = driver.findElement(By.xpath("//div[contains(@class,'nav-statistics')]//a[contains(@href,'follow')]//span[contains(@class,'item-num')]"));
                userInfo.put("follow", followElement.getText().replace(",", ""));
            } catch (Exception e) {
                userInfo.put("follow", "0");
            }

            try {
                WebElement fansElement = driver.findElement(By.xpath("//div[contains(@class,'nav-statistics')]//a[contains(@href,'fans')]//span[contains(@class,'item-num')]"));
                userInfo.put("fans", fansElement.getText().replace(",", ""));
            } catch (Exception e) {
                userInfo.put("fans", "0");
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("获取用户信息失败: " + e.getMessage());
        } finally {
            try {
                // 移除Thread.sleep，确保快速关闭
                driver.quit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return userInfo;
    }

    public static User getUser(String uid) {
        Map<String, String> userInfo = getUserInfoByUid(uid);

        if (userInfo.isEmpty()) {
            throw new RuntimeException("找不到对uid应用户，用户不存在或用户已注销");//或者cookies过期
        }
        User user = new User();
        user.setUid(uid);
        user.setUsername(userInfo.get("username"));
        user.setLevel(Integer.parseInt(userInfo.get("level")));
        user.setGender(userInfo.get("gender"));
        user.setFanMedal(userInfo.get("medal"));
        user.setFansCount(parseNumber(userInfo.get("fans")));
        user.setFollowCount(Integer.parseInt(userInfo.get("follow")));

        return user;
    }
}
